<template>
    <NButton v-bind="mergedProps" v-if="visible()" @click="handleClick">
        <template v-if="title && !$slots['default']">{{ title }}</template>
        <template #[item]="data" v-for="item in Object.keys($slots)" :key="item">
            <slot :name="item" v-bind="data || {}"> </slot>
        </template>
    </NButton>
</template>

<script setup lang="ts">
import { isFunction, isString, isUndefined, renderAntIcon, renderIcon } from "@/utils"
import type { GetanButtonProps } from "./types"
import { hasPermission, isDisabled, isShow } from "@/components/Permission"

const props = defineProps<{
    options?: GetanButtonProps
}>()

const status = ref<{ loading: boolean; disabled: boolean }>({ loading: false, disabled: false })

const naiveProps = computed(() => {
    const p: Recordable = { loading: status.value.loading }
    if (props.options) {
        const { icon, type, block, shape, size, tag, border } = props.options as GetanButtonProps
        p.type = type
        p.size = size
        p.tag = tag
        p.block = block
        if (icon) {
            if (isString(icon)) {
                p.renderIcon = renderAntIcon(icon as string)
            } else if (isFunction(icon)) {
                p.renderIcon = icon
            } else {
                p.renderIcon = renderIcon(icon as Component)
            }
        }
        if (shape === "circle") {
            p.circle = true
        } else if (shape === "round") {
            p.round = true
        }
        if (border === "dashed") {
            p.dashed = true
        } else if (border === "text") {
            p.text = true
        } else {
            p.bordered = true
        }
        p.disabled = isDisabled(props.options, false, props.options.data)
    }
    return p
})

const attrs = useAttrs()

const mergedProps = computed(() => {
    return {
        ...attrs,
        ...unref(naiveProps)
    }
})

const title = computed(() => props.options?.title)

const visible = () => {
    if (props.options) {
        return isShow(props.options, true, props.options.data) && hasPermission(props.options)
    }
    return true
}

const handleClick = async () => {
    if (isUndefined(attrs.onClick) && props.options) {
        const { onClick } = props.options
        if (isFunction(onClick)) {
            ;(onClick as Function)(props.options.data, status)
        }
    }
}
</script>
